package com.hnucm.c201901020241.discuss;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Base64;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.app.hubert.guide.NewbieGuide;
import com.app.hubert.guide.core.Controller;
import com.app.hubert.guide.listener.OnGuideChangedListener;
import com.app.hubert.guide.listener.OnPageChangedListener;
import com.app.hubert.guide.model.GuidePage;
import com.app.hubert.guide.model.HighLight;
import com.bumptech.glide.Glide;
import com.hnucm.c201901020241.R;
import com.hnucm.c201901020241.fragment.DongtaiFragment;
import com.hnucm.c201901020241.pojo.PostInformation;
import com.scwang.smart.refresh.footer.ClassicsFooter;
import com.scwang.smart.refresh.header.ClassicsHeader;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnLoadMoreListener;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
//该类用来记录每一个帖子的详细信息，包括发帖人，发的帖子名称和内容。以及下方的评论区。
//对于评论区的评论功能，是否需要新开一个表？
//先将评论区的基本功能完成，暂时不完成对于评论的评论，仅完成评论楼主的功能。

public class Discuss_post_information extends AppCompatActivity {
//    当前文章标题和发帖人，发帖时间，在数据库中建立一个表来记录每一个帖子中的详细回复信息
//    发帖时间和回复时间要分清楚
//    account是发帖人账号，account_floor是评论人账号
//    每增加一条数据，我们需要传递的参数有  回复人name，回复内容information， 回复事件time_floor,头像image_floor，帖子id通过上面三个获得，楼层自动生成
//    上述这些数据我们都需要封装到类里面。
    String title_discuss,time,mainInformation,information,name_floor,time_floor,account,name,base64,base64_floor,account_floor;
    TextView title_discussTv,nameTv,timeTv,mainInformationTv;
    ImageView imageTv,back,add;
    Button submit;
    List<PostInformation>postInformationList;
    RecyclerView recyclerView;
    MyAdapter myAdapter;
    private String TAG = Discuss_post_information.class.getSimpleName();

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(data!=null) information=data.getStringExtra("information");
        else information=null;
        if(information!=null) {
            //        在这里获得了回传值之后，将评论的数据上传
            Date date=new Date();
            SimpleDateFormat sdf=new SimpleDateFormat("MM-dd HH:mm:ss");
            time_floor=sdf.format(date);
            x.Ext.init(getApplication());
            RequestParams requestParams = new RequestParams("http://121.4.27.254:8090/addPostInformation?");
            requestParams.addQueryStringParameter("title_discuss", title_discuss);
            requestParams.addQueryStringParameter("name", name);
            requestParams.addQueryStringParameter("time", time);
            requestParams.addQueryStringParameter("name_floor", name_floor);
            requestParams.addQueryStringParameter("information", information);
            requestParams.addQueryStringParameter("time_floor", time_floor);
            requestParams.addQueryStringParameter("account_floor",account_floor);
//            把所有发送base64的请求都删掉这一句话，将请求简化
//            requestParams.addQueryStringParameter("base64_floor", base64_floor);
            requestParams.addQueryStringParameter("account",account);
            x.http().post(requestParams, new Callback.CommonCallback<String>() {
                @Override
                public void onSuccess(String result) {
                    if (result.equals("1"))
                        Toast.makeText(Discuss_post_information.this, "评论成功", Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onError(Throwable ex, boolean isOnCallback) {
                    Toast.makeText(Discuss_post_information.this, "网络出现异常错误，请稍后", Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onCancelled(CancelledException cex) {
                }

                @Override
                public void onFinished() {

                }
            });
        }


    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_discuss_post_information);

        init_String();
        init_action();

//        接下来发送请求获得对应帖子的数据，然后放在RecyclerView中
        x.Ext.init(getApplication());
        RequestParams requestParams = new RequestParams("http://121.4.27.254:8090/queryPostInforList?");
        requestParams.addQueryStringParameter("title_discuss",title_discuss);
        requestParams.addQueryStringParameter("account",account);
        requestParams.addQueryStringParameter("time",time);
        x.http().get(requestParams, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Log.i("Discuss_post","result:"+result);
                try {
                    JSONArray jsonArray=new JSONArray(result);
                    for(int i=0;i<jsonArray.length();i++){
                        PostInformation postInformation = new PostInformation();
                        JSONObject jsonObject=jsonArray.getJSONObject(i);
                        postInformation.setName_floor(jsonObject.getString("name_floor"));
                        postInformation.setInformation(jsonObject.getString("information"));
                        postInformation.setContent_id(jsonObject.getInt("content_id"));
                        postInformation.setBase64_floor(jsonObject.getString("base64_floor"));
                        postInformation.setTime_floor(jsonObject.getString("time_floor"));
                        postInformation.setFloor(jsonObject.getInt("floor"));
                        postInformation.setAccount_floor(jsonObject.getString("account_floor"));
                        postInformation.setAccount(jsonObject.getString("account"));
                        postInformationList.add(postInformation);
                    }
                    myAdapter=new MyAdapter();
                    recyclerView.setAdapter(myAdapter);
                    recyclerView.setLayoutManager(new LinearLayoutManager(Discuss_post_information.this));
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Log.i("Discuss_post","error:"+ex);
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });



//        刷新功能
        RefreshLayout refreshLayout = (RefreshLayout)findViewById(R.id.SmartRefreshLayout3);
        refreshLayout.setRefreshHeader(new ClassicsHeader(this));
        refreshLayout.setRefreshFooter(new ClassicsFooter(this));
//        上拉加载
        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(RefreshLayout refreshLayout) {
                refreshLayout.finishLoadMore(2000/*,false*/);//传入false表示加载失败
            }
        });
//        下拉刷新
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                //        接下来发送请求获得对应帖子的数据，然后放在RecyclerView中
                postInformationList.clear();
                x.Ext.init(getApplication());
                RequestParams requestParams = new RequestParams("http://121.4.27.254:8090/queryPostInforList?");
                requestParams.addQueryStringParameter("title_discuss",title_discuss);
                requestParams.addQueryStringParameter("account",account);
                requestParams.addQueryStringParameter("time",time);
                x.http().get(requestParams, new Callback.CommonCallback<String>() {
                    @Override
                    public void onSuccess(String result) {
                        Log.i("Discuss_post","result:"+result);
                        try {
                            JSONArray jsonArray=new JSONArray(result);
                            for(int i=0;i<jsonArray.length();i++){
                                PostInformation postInformation = new PostInformation();
                                JSONObject jsonObject=jsonArray.getJSONObject(i);
                                postInformation.setName_floor(jsonObject.getString("name_floor"));
                                postInformation.setInformation(jsonObject.getString("information"));
                                postInformation.setContent_id(jsonObject.getInt("content_id"));
                                postInformation.setTime_floor(jsonObject.getString("time_floor"));
                                postInformation.setBase64_floor(jsonObject.getString("base64_floor"));
                                postInformation.setFloor(jsonObject.getInt("floor"));
                                postInformation.setAccount(jsonObject.getString("account"));
                                postInformationList.add(postInformation);
                            }
                            myAdapter.notifyDataSetChanged();
                            refreshLayout.finishRefresh(2000/*,false*/);//传入false表示刷新失败
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }

                    @Override
                    public void onError(Throwable ex, boolean isOnCallback) {
                        Log.i("Discuss_post","error:"+ex);
                    }

                    @Override
                    public void onCancelled(CancelledException cex) {

                    }

                    @Override
                    public void onFinished() {

                    }
                });
            }
        });
        SharedPreferences sharedPreferences=getSharedPreferences("user",MODE_MULTI_PROCESS);
        boolean addisselected = sharedPreferences.getBoolean("addisselected", false);
        if(!addisselected) {
            SharedPreferences.Editor editor = sharedPreferences.edit();
            editor.putBoolean("addisselected", true);
            editor.commit();
            init_NewbieGuide();
        }
    }
    private void init_NewbieGuide() {
        Animation enterAnimation = new AlphaAnimation(0f, 1f);
        enterAnimation.setDuration(600);
        enterAnimation.setFillAfter(true);

        Animation exitAnimation = new AlphaAnimation(1f, 0f);
        exitAnimation.setDuration(600);
        exitAnimation.setFillAfter(true);

        NewbieGuide.with(this)
                .setLabel("Dongtai_post_information")//设置引导层标示区分不同引导层，必传！否则报错
                .setShowCounts(1)
                .setOnGuideChangedListener(new OnGuideChangedListener() {//引导层显示监听
                    @Override
                    public void onShowed(Controller controller) {
                        Log.e(TAG, "NewbieGuide onShowed: ");
                        //引导层显示
                    }

                    @Override
                    public void onRemoved(Controller controller) {//引导层隐藏监听
                        Log.e(TAG, "NewbieGuide  onRemoved: ");
                        //引导层消失（多页切换不会触发）
                    }
                })
                .setOnPageChangedListener(new OnPageChangedListener() {//引导页切换监听
                    @Override
                    public void onPageChanged(int page) {
                        Log.e(TAG, "NewbieGuide  onPageChanged: " + page);
                        //引导页切换，page为当前页位置，从0开始
                    }
                })
                .alwaysShow(true)//是否每次都显示引导层，默认false，只显示一次
                /**
                 * 添加引导页一
                 */
                .addGuidePage(//添加一页引导页
                        GuidePage.newInstance()//创建一个实例
                                .addHighLight(add)//添加高亮的view
                                .addHighLight(add, HighLight.Shape.RECTANGLE)
                                .setLayoutRes(R.layout.discuss_post_information_style)//设置引导页布局
                                .setEnterAnimation(enterAnimation)//进入动画
                                .setExitAnimation(exitAnimation)//退出动画*/
                )


                /**
                 * 展示
                 */
                .show();//显示引导层(至少需要一页引导页才能显示)
    }


    private void init_action() {
//        返回事件
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
//        回复，我的初步设想并不麻烦，回复的内容也是作为一个单独的内容显示，所以只需要会点击回复弹出输入框就好了。
        add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });

        submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent(Discuss_post_information.this, DialogActivity.class);
                startActivityForResult(intent,0);
//                Log.i("Discuss_post",information);

            }
        });
    }

    private void init_String(){

        postInformationList=new ArrayList<PostInformation>();
        title_discuss=getIntent().getStringExtra("title_discuss");
        name=getIntent().getStringExtra("name");
        time=getIntent().getStringExtra("time");
//        image=getIntent().getStringExtra("image");
        account=getIntent().getStringExtra("account");
        base64=getIntent().getStringExtra("base64");
//        当前评论的人的name
        SharedPreferences sharedPreferences=getSharedPreferences("user",MODE_PRIVATE);
        name_floor = sharedPreferences.getString("name", "test");
        base64_floor=sharedPreferences.getString("base64","null");//用于当前用户的评论时使用
        account_floor=sharedPreferences.getString("account","");
        //传上述的四个数据传递到数据库来确定唯一标识
        mainInformation=getIntent().getStringExtra("mainInformation");

        recyclerView=findViewById(R.id.recyclerview2);
        submit=findViewById(R.id.submit);
        back=findViewById(R.id.imageview12);
        add=findViewById(R.id.imageview13);
        title_discussTv=findViewById(R.id.textView21);
        nameTv=findViewById(R.id.textView19);
        timeTv=findViewById(R.id.textView26);
        mainInformationTv=findViewById(R.id.textView23);
        imageTv=findViewById(R.id.imageView9);
//        还有一个textView22  暂时不用，可以用来记录每个人的一个个性签名

        title_discussTv.setText(title_discuss);
        nameTv.setText(name);
        timeTv.setText(time);
        mainInformationTv.setText(mainInformation);

        byte[] imageBytes = Base64.decode(base64, Base64.DEFAULT);
        Bitmap decodedImage = BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.length);
        imageTv.setImageBitmap(decodedImage);
    }

    public class MyAdapter extends RecyclerView.Adapter<MyViewHolder> {

        @NonNull
        @Override
        public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(Discuss_post_information.this).inflate(R.layout.post_information_item, parent, false);

            MyViewHolder myViewHolder = new MyViewHolder(view);

            return myViewHolder;
        }

        @Override
        public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {
            holder.nameTv.setText(postInformationList.get(position).getName_floor());
            holder.inforTv.setText(postInformationList.get(position).getInformation());
            holder.timeTv.setText(postInformationList.get(position).getTime_floor());
            holder.floorTv.setText((postInformationList.size()-position)+"楼");
//            加载base64图片
            byte[] imageBytes = Base64.decode(postInformationList.get(position).getBase64_floor(), Base64.DEFAULT);
            Bitmap decodedImage = BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.length);
            holder.imageView.setImageBitmap(decodedImage);
//            Glide.with(Discuss_post_information.this).load(postInformationList.get(position).getImage()).into(holder.imageView);
        }

        @Override
        public int getItemCount() {
            return postInformationList.size();
        }
    }


    public class MyViewHolder extends RecyclerView.ViewHolder {
        TextView nameTv,inforTv,timeTv,floorTv;
        ImageView imageView;
        public MyViewHolder(@NonNull View itemView) {
            super(itemView);
            floorTv=itemView.findViewById(R.id.textView31);
            nameTv = itemView.findViewById(R.id.textView28);
            inforTv = itemView.findViewById(R.id.textView30);
            timeTv = itemView.findViewById(R.id.textView33);
            imageView = itemView.findViewById(R.id.imageView11);
        }
    }


}